package com.loren.demo03.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class HttpSocketServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext context, HttpObject msg) {
        if (msg instanceof HttpRequest) {

            System.out.println("remoteAddress = " + context.channel().remoteAddress()
                    + "，pipelineHashCode = " + context.pipeline().hashCode() + "，hashCode = " + this.hashCode());

            ByteBuf byteBuf = Unpooled.copiedBuffer("Hello Netty Server", CharsetUtil.UTF_8);

            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

            HttpHeaders headers = response.headers();
            headers.set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            headers.set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            context.writeAndFlush(response);
        }
    }
}
